import { login as loginApi } from "@/api/login"
import router from "@/router"
import { setTokenTime } from "@/utils/auth"
import { ElMessage } from "element-plus"

export default {
  namespaced: true,
  state: () => ({
    token: localStorage.getItem("token") || "",
    siderType: true,
    lang: localStorage.getItem("lang") || "zh",
  }),
  mutations: {
    // 设置token
    setToken(state, token) {
      state.token = token
      localStorage.setItem("token", token)
    },

    // 开启与关闭侧边栏
    changeSiderType(state) {
      state.siderType = !state.siderType
    },

    // 更改语言
    changLang(state, lang) {
      state.lang = lang
    },
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginApi(userInfo)
          .then((res) => {
            // console.log(res)
            commit("setToken", res.token)
            setTokenTime()
            ElMessage({ type: "success", message: "登录成功" })
            router.replace("/")
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },

    // 退出登录
    logout({ commit }) {
      commit("setToken", "")
      localStorage.clear()
      router.replace("/login")
    },
  },
}
